package com.yds.bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.util.Log
import java.io.IOException
import java.util.*

/**
 * 连接经典蓝牙
 */
@Suppress("Unused")
internal object ConnectClassicDeviceManager {
    private const val TAG = "YDS蓝牙"

    // 经典蓝牙标准UUID
    private var serviceUuid = "00001101-0000-1000-8000-00805F9B34FB"

    private var bluetoothAdapter: BluetoothAdapter? = null
    private var connectedThread: ConnectedThread? = null
    private var deviceAddress: String? = null

    /**
     * 连接到经典蓝牙设备
     */
    fun connectToDevice(device: BluetoothDevice, resultCallback: (Boolean) -> Unit, serviceUuid: String = "00001101-0000-1000-8000-00805F9B34FB") {
        this.serviceUuid = serviceUuid

        val socket = device.createRfcommSocketToServiceRecord(UUID.fromString(serviceUuid))
        bluetoothAdapter?.cancelDiscovery()
        Thread {
            try {
                socket.connect()
                deviceAddress = device.address
                connectedThread = ConnectedThread(socket)
                connectedThread?.start()
                resultCallback.invoke(true)
                Log.i(TAG, "连接蓝牙设备：$deviceAddress ${device.type}")
            } catch (e: IOException) {
                e.printStackTrace()
                resultCallback.invoke(false)
                Log.e(TAG, "连接蓝牙设备IOException：" + e.message)
            }
        }.start()
    }

    class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {
        private val mmInStream = mmSocket.inputStream
        private val mmOutStream = mmSocket.outputStream
        private val mBuffer: ByteArray = ByteArray(1024 * 4)

        override fun run() {
            while (true) {
                try {
                    val mBufDataLen = mmInStream.read(mBuffer)
                    val newBuf = ByteArray(mBufDataLen)
                    System.arraycopy(mBuffer, 0, newBuf, 0, mBufDataLen)
                    receiveResultCallback?.invoke(newBuf)
                } catch (e: IOException) {
                    break
                }
            }
        }

        fun write(buffer: ByteArray) {
            try {
                mmOutStream.write(buffer)
                sendResultCallback?.invoke(true)
            } catch (e: IOException) {
                e.printStackTrace()
                Log.e(TAG, "经典蓝牙 write IOException = " + e.message)
                sendResultCallback?.invoke(false)
            }
        }

        fun cancel() {
            try {
                mmSocket.close()
            } catch (e: IOException) {
                e.printStackTrace()
                Log.e(TAG, "经典蓝牙 cancel IOException = " + e.message)
            }
        }
    }

    // 蓝牙设备发送数据结果回调
    private var sendResultCallback: ((Boolean) -> Unit)? = null

    // 蓝牙设备返回数据结果回调
    private var receiveResultCallback: ((ByteArray) -> Unit)? = null

    /**
     * 发送数据到经典蓝牙设备
     */
    fun sendDataToBleDevice(data: ByteArray, sendResultCallback: (Boolean) -> Unit, receiveResultCallback: (ByteArray) -> Unit) {
        this.sendResultCallback = sendResultCallback
        this.receiveResultCallback = receiveResultCallback
        connectedThread?.write(data)
    }

    /**
     * 断开与经典蓝牙设备的连接
     */
    fun disconnectFromDevice() {
        connectedThread?.cancel()
    }

}